using System;
using Graphe.RobinsonPierpont;

namespace Graphe.Tools.TextualRangeGuesser
{
    public class Guesser
    {
        private static CollapsedVerseCollection _verses = new CollapsedVerseCollection();

        public static string Guess(int columns, int charactersPerLine, int lines, string bookName, int chapterNumber, int verseNumber, bool includeSpaces, bool includePunctuation)
        {
            if (_verses.Count == 0)
            {
                BookCollection books = Parser.Parse();

                foreach (Book book in books)
                {
                    foreach (Chapter chapter in book.Chapters)
                    {
                        foreach (Verse verse in chapter.Verses)
                        {
                            CollapsedVerse collapsedVerse = new CollapsedVerse();

                            string chNumber = chapter.Number.ToString();
                            string vNumber = verse.Number.ToString();

                            if (chapter.Number <= 9)
                                chNumber = chNumber.Insert(0, "0");
                            if (verse.Number <= 9)
                                vNumber = vNumber.Insert(0, "0");

                            collapsedVerse.Reference = book.Name + " " + chNumber + ":" + vNumber;
                            collapsedVerse.Verse = verse;

                            _verses.Add(collapsedVerse);
                        }
                    }
                }
            }

            int totalCharacters = columns * lines * charactersPerLine;

            int index = _verses.IndexOf(bookName, chapterNumber, verseNumber);
            int currentCharacterCount = 0;
            CollapsedVerse currentVerse = null;

            while (currentCharacterCount <= totalCharacters)
            {
                currentVerse = _verses[index];

                currentCharacterCount += currentVerse.Verse.GetCharacterCount(includeSpaces, includePunctuation);

                if (currentCharacterCount > totalCharacters)
                    break;

                index++;
            }

            return currentVerse.Reference;
        }



    }
}
